package com.examlpe.cels.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.examlpe.cels.entity.Vocabulary;
import com.examlpe.cels.entity.Word;
import com.examlpe.cels.mapper.VocabularyMapper;
import com.examlpe.cels.mapper.WordMapper;
import com.examlpe.cels.service.IBrowserService;
import com.examlpe.cels.util.MybatisUtils;
import com.examlpe.cels.util.PageBean;

public class BrowserServiceImpl implements IBrowserService {

//	private static SqlSessionFactory ssf;
//	public SqlSessionFactory se() {
//	String resource = "MybatisConfig.xml";
//	InputStream input;
//	try {
//		input = Resources.getResourceAsStream("MybatisConfig.xml");
//		ssf = new SqlSessionFactoryBuilder().build(input);
//	} catch (IOException e) {
//		e.printStackTrace();
//	}
//	return ssf;
//	}
	
	//@Override
	public Map<Character, Set<Word>> getFirstMap() {
		Map<Character, Set<Word>> datas = new TreeMap<Character, Set<Word>>();
//			SqlSession ss = ssf.openSession();
			SqlSession ss =MybatisUtils.getSqlSession();
			WordMapper wm = ss.getMapper(WordMapper.class);
//			Set<Word> words = wm.findAllWord();
			Set<Word> wSet = wm.findAllWord();
			Set<Word> set = null;
			for(Word w:wSet) {
				if(datas.containsKey(w.getFirst())) {
				  set = datas.get(w.getFirst());
				  set.add(w);
				  datas.put(w.getFirst(), set);
				}else {
				  set = new TreeSet<Word>();
				  set.add(w);
				  datas.put(w.getFirst(), set);
				}
			}
		return datas;
	}

	//@Override
	public PageBean getPageVocabularies() {
		Set<Vocabulary> datas  = null;
//			SqlSession ss = ssf.openSession();
			SqlSession ss = MybatisUtils.getSqlSession();
			// Mapper接口对象
			VocabularyMapper vm = ss.getMapper(VocabularyMapper.class);
//			Set<Vocabulary> vocabularys 
			datas= vm.findAllVocabulary();
		int pageSize = IBrowserService.PAGE_SIZE;
		PageBean pb = new PageBean(datas, pageSize); 
		return pb;
	}

}
